<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" href="./layui/css/layui.css">
		<script src="./layui/layui.js"></script>
		<script type="text/javascript" src="js/global.js"></script>
		<script src="js/jquery-2.1.1.min.js"></script>
	</head>
	<body>
		
		<input type="text" id="text" />
		<input type="button" value="发送" onclick="sendMS()" />
		<input type="button" value="关闭" onclick="closeMS()" />
		<div id="res">
			
		</div>
		<script>
			
			// 1、创建socket对象
			var ws = null;
			var res = document.getElementById("res");
			if('WebSocket' in window){
				ws = new WebSocket("ws://localhost:8080/mySocket");
			}else{
				alert("您的浏览器不支持websocket")
			}
			
			ws.onopen=function(){
				res.innerHTML+="链接已经打开"+"<br>";

			}
			
			ws.onclose=function(){
				res.innerHTML+="链接已经关闭"+"<br>";
				//关闭链接
				ws.close();
			}
			
			ws.onerror=function(){
				res.innerHTML+="链接异常"+"<br>";
			}
			
			//当接收到服务器信息触发该方法
			ws.onmessage=function(event){
				//获取服务端的信息
				var val = event.data;
				var v = val.split(":");
				var k = null;
				var v = null;
					console.log(val);
				$.each(val.split(":"),function(i,res){
					if(i==0){
						k = res;
					}else{
						v = res;
					}
				});
				res.innerHTML+=k+"说："+v+"<br>";
			}
			
			function sendMS(){
				var v = document.getElementById("text").value;
				console.log(v);
				//给服务端发信息
				ws.send(v);
			}
			
			function closeMS(){
				ws.close();
			}
		</script>
		
	</body>
</html>
